package com.vf.cloud.paas.app.agent.common.server.signalling.player;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import com.vf.cloud.paas.app.agent.common.server.signalling.channel.PlayerChannelInitializer;
import com.vf.cloud.paas.common.cirrus.Cirrus;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class PlayerServer {

	@Value("${agent.install.path}")
	private String installPath;

	private EventLoopGroup boss;
	private EventLoopGroup work;
	private Channel channel;

	@Async
	public void run() {
		try {
			if(Cirrus.playerIsConnected) {
				destroy();
			}
			if(Cirrus.Player_Port==0) {
				log.info(">>> PlayerServer:配置有误，请检查端口.");
				return;
			}
			
			ServerBootstrap bootstrap = new ServerBootstrap();
			boss = new NioEventLoopGroup();
			work = new NioEventLoopGroup();

			log.info(String.format(">>> PlayerServer:开始启动[%s]." ,Cirrus.Player_Port));
			bootstrap.group(boss, work);
			bootstrap.channel(NioServerSocketChannel.class);
			bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(512 * 1024, 1024 * 1024));
			bootstrap.childHandler(new PlayerChannelInitializer());
			channel = bootstrap.bind(Cirrus.Player_Port).sync().channel();
			log.info(String.format(">>> PlayerServer listening on *:%s." ,Cirrus.Player_Port));
			
			Cirrus.playerIsConnected=true;
			if(channel!=null  && channel.closeFuture()!=null) {
				channel.closeFuture().sync();
			}
		} catch (Exception e) {
		} finally {
			if(channel!=null) channel.close();
			if(work!=null) work.shutdownGracefully();
			if(boss!=null) boss.shutdownGracefully();
			log.info(String.format(">>> PlayerServer:已停止[%s].", Cirrus.Player_Port));
		}
	}

	public void destroy() {
		if(channel!=null) {
			channel.close();
		}
		if(work!=null) {
			work.shutdownGracefully();
		}
		if(boss!=null) {
			boss.shutdownGracefully();
		}
		Cirrus.playerIsConnected=false;
	}

}
